<template>
    <div>
        <el-cascader
            ref="areaCascade"
            :value="value.code"
            :options="areaData"
            :props="props"
            collapse-tags
            clearable
            separator=" "
            @change="handleChange"
            style="width: 300px"
        />
    </div>
</template>
<script>
const areaList = require('./area')
import _ from 'lodash'

export default {
    props: {
        value: {
            type: Object,
            default: () => {
            }
        }
    },
    data() {
        return {
            areaData: areaList,
            props: {
                multiple: false, // 是否多选
                label: 'name',
                value: 'code',
                children: 'children'
            }
        }
    },
    watch: {
        // 数据回显
        value: {
            immediate: true,
            handler(val) {
                const {provinceCode, cityCode, countryCode} = val
                val.code = []
                val.code.push(provinceCode)
                if (cityCode !== '') val.code.push(cityCode)
                if (countryCode !== '') val.code.push(countryCode)
                return val
            }
        }
    },
    created() {
    },
    methods: {
        // 初始化省市区数据
        handleChange(value) {
            const checkedNode = this.$refs.areaCascade.getCheckedNodes()[0];
            const _value = _.cloneDeep(value) // 数据深克隆  避免回显问题
            if (_value.length !== 0) {
                const result = {
                    address: checkedNode.pathLabels.join(''),
                    province: checkedNode.pathLabels[0],
                    provinceCode: _value[0],
                    city: checkedNode.pathLabels[1] !== undefined ? checkedNode.pathLabels[1] : '',
                    cityCode: _value[1] !== undefined ? _value[1] : '',
                    country: checkedNode.pathLabels[2] !== undefined ? checkedNode.pathLabels[2] : '',
                    countryCode: _value[2] !== undefined ? _value[2] : ''
                }
                this.$emit('input', result)
            }
        }
    }
}
</script>
